External Exam Download Resources Web Applications Games Recycle Bin

Jinja2 for loops

server.py

from flask import *
app = Flask("iteration in jinja")

ministers = ["ScoMo", "Turnbull", "Julia"]

@app.route("/")
def main():
    return render_template("template.html",
                           names = ministers)
 
app.run(debug=True)

templates\template.html

<table border="1">
  <tr><td>Prime Minister</td></tr>
  {% for n in names %}
    <tr><td>{{n}}</td></tr>
  {% endfor %}
</table>

you can also loop through a tuple, or a dictionary:

server.py

from flask import *
app = Flask("more iteration in jinja")

ministers = {
    "ScoMo":"Liberal",
    "Turnbull":"Liberal",
    "Julia":"Labor"
}

@app.route("/")
def main():
    return render_template("template.html",
                           names = ministers)
 
app.run(debug=True)

templates\template.html

<table border="1">
  <tr><td>Prime Minister</td><td>Party</td></tr>
  {% for n in names|sort %}
    <tr><td>{{n}}</td><td>{{names[n]}}</td></tr>
  {% endfor %}
</table>